package com.myacg.core.task;

import java.util.Date;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 倒计时任务管理器
 * @author Administrator
 *
 */
public class CountDownTaskManager {
	private ConcurrentMap<String, CountDownTask>  map;
	private boolean ispause;
	private static CountDownTaskManager countDownTaskManage;
	private int i;
	private CountDownTaskManager(){
		 map= new ConcurrentHashMap<>();
		//启动定时任务
		startAllTask();
	}
	
	public void continueTasks(){
		ispause=false;
	}
	public void pauseTasks(){
		ispause=true;
	}
	
	/**
	 * 获取倒计时任务管理器
	 * @return
	 */
	public static CountDownTaskManager getInstance(){
		if(countDownTaskManage==null){
			countDownTaskManage=new CountDownTaskManager();
		}
		return countDownTaskManage;
	}
	
	/**
	 * 加入一个任务并为该任务 分配一个id
	 * @param task
	 */
	public synchronized void addTask(CountDownTask task){
		if(task.getId()==null){
			task.id=("CD-"+new Date().getTime()+"-"+i++);
			this.map.put(task.getId(), task);
			System.out.println("add CountDownTask: "+ task.id);
		}
	}
    
 
	/**
	 * 启动所有任务的方法
	 */
	private void startAllTask(){
		new Thread( new  Runnable() {
			 
			public void run() {
				while(true){
				synchronized (map) { 
				 //执行队列中尚存在的任务	
					 if(!ispause){
						Set<String> set = map.keySet();
						   for (String key : set) {
							     CountDownTask task = map.get(key);
							     if(task.initSecond==0){
							    	 map.remove(task.getId()); //移除
							    	 task.overExecute();
							     }else if(task.initSecond%task.howSecond == 0){ //每到howSecond 个间隔 执行一次
							    	 task.excute();
							     }
							     task.initSecond--;
						   }
					 }
				   //休眠一毫秒
			       try { Thread.sleep(1); } catch (InterruptedException e) { }
					
				}
		 
			 }
		 }
		}).start();
		
		
	}
	
	/**
	 * 返回当前状态
	 * @return
	 */
	public  boolean  isPause(){
		return this.ispause;
	}
	
	/**
	 * Demo
	 * @param args
	 */
	public static void main(String[] args) {
		CountDownTaskManager.getInstance();
		
		CountDownTaskManager.getInstance().addTask(new CountDownTask(5000, 500) {
			@Override
			public void secondExecute() {
				System.out.println("secondExecute");
			}
			@Override
			public void overExecute() {
				System.out.println("overExecute");
			}
			 
		}); 
		 
	}
	
	
}
